<template>
	<div class="layout-padding">
		<div class="layout-padding-auto layout-padding-view">
			<el-row>
				<div class="flex justify-between w-full mb8">
					<el-space>
						<el-popover trigger="click" :width="360" placement="bottom-start">
							<el-form :inline="false" :model="state.queryForm" @keyup.enter="getDataList" ref="queryRef" label-width="70px">
								<el-row>
									<el-col :span="24" class="mb-4">
										<el-form-item label="所属单位" prop="deptId">
											<el-tree-select
												v-model="state.queryForm.deptId"
												:data="parentData"
												:props="{ value: 'id', label: 'name', children: 'children', disabled: 'isLock' }"
												clearable
												filterable
												check-strictly
												:render-after-expand="false"
												placeholder="请选择所属单位"
												:teleported="false"
											/>
										</el-form-item>
									</el-col>
									<el-col :span="24" class="mb-4">
										<el-form-item label="单位限制" prop="deptLimit">
											<el-select v-model="state.queryForm.deptLimit" clearable placeholder="请选择单位限制" :teleported="false">
												<el-option :value="10" label="包含下级单位设备" />
												<el-option :value="20" label="仅本单位设备" />
											</el-select>
										</el-form-item>
									</el-col>
									<el-col :span="24" class="mb-4">
										<el-form-item label="建筑物" prop="buildingId">
											<el-select v-model="state.queryForm.buildingId" filterable placeholder="请选择" @change="handleBuildChange" :teleported="false">
												<el-option v-for="item in buildingOptions" :key="item.id" :label="item.buildingName" :value="item.id" />
											</el-select>
										</el-form-item>
									</el-col>
									<el-col :span="24" class="mb-4">
										<el-form-item label="楼层" prop="floorId">
											<el-select
												v-model="state.queryForm.floorId"
												filterable
												placeholder="请选择"
												:disabled="!state.queryForm.buildingId"
												:teleported="false"
											>
												<el-option v-for="item in floorOptions" :key="item.id" :label="item.floorName" :value="item.id" />
											</el-select>
										</el-form-item>
									</el-col>
									<el-col :span="24" class="mb-4">
										<el-form-item label="安装人" prop="installWorker">
											<el-input v-model="state.queryForm.installWorker" placeholder="请输入" maxlength="50" />
										</el-form-item>
									</el-col>
									<el-col>
										<el-form-item label="安装日期" prop="createTime">
											<el-date-picker
												:end-placeholder="$t('syslog.inputEndPlaceholderTip')"
												:start-placeholder="$t('syslog.inputStartPlaceholderTip')"
												range-separator="To"
												type="datetimerange"
												v-model="state.queryForm.createTime"
												value-format="YYYY-MM-DD HH:mm:ss"
												:teleported="false"
											/>
										</el-form-item>
									</el-col>
								</el-row>
							</el-form>

							<template #reference>
								<el-button link type="primary"
									>高级搜索<el-icon><ArrowDown /></el-icon>
								</el-button>
							</template>
						</el-popover>
						<el-input placeholder="请输入IMEI号" v-model="state.queryForm.imei" />
						<el-button type="primary" @click="getDataList(true)">搜索</el-button>
						<el-button icon="refresh" @click="resetQuery()"></el-button>
					</el-space>
					<div>
						<el-button type="success" class="mr-2" @click="formDialogRef.openDialog(_, false)"> 新增</el-button>
						<!-- 更多操作 -->
						<el-popover :width="168">
							<template #reference>
								<el-button type="primary"
									>更多操作 <el-icon class="ArrowDown"><ArrowDown /></el-icon></el-button
							></template>
							<el-row>
								<el-col :span="24">
									<el-button
										class="ml-3"
										text
										icon="edit"
										type="primary"
										:disabled="multiple || selectObjs.length !== 1"
										@click="formDialogRef.openDialog(selectObjs[0], true)"
										>修改安装点</el-button
									>
									<el-button text icon="delete" type="danger" :disabled="multiple" @click="visible = true">解绑安装点</el-button>
								</el-col>
							</el-row>
						</el-popover>
					</div>
				</div>
			</el-row>
			<el-table
				:data="state.dataList"
				v-loading="state.loading"
				border
				:cell-style="tableStyle.cellStyle"
				:header-cell-style="tableStyle.headerCellStyle"
				@selection-change="selectionChangHandle"
				@sort-change="sortChangeHandle"
			>
				<el-table-column type="selection" width="40" align="center" />
				<el-table-column type="index" label="序号" width="60" />
				<el-table-column prop="address" label="安装点名称" show-overflow-tooltip width="200">
					<template #default="{ row }">
						<el-button link size="small" type="primary" @click="detailDialogRef.openDialog(row.id)">{{ row.address }}</el-button>
					</template>
				</el-table-column>
				<el-table-column prop="buildingName" label="建筑物" show-overflow-tooltip width="150">
					<template #default="{ row }">
						<el-button link size="small" type="primary" @click="handleBuilding(row.buildingId)">{{ row.buildingName }}</el-button>
					</template>
				</el-table-column>
				<el-table-column prop="floor" label="楼层" show-overflow-tooltip>
					<template #default="{ row }">
						<el-button link size="small" type="primary" @click="handleFloor(row)">{{ row.floor }}</el-button>
					</template>
				</el-table-column>
				<el-table-column prop="imei" label="IMEI" show-overflow-tooltip width="150">
					<template #default="{ row }">
						<el-button link size="small" type="primary" @click="handleDetail(row)">{{ row.imei }}</el-button>
					</template>
				</el-table-column>
				<el-table-column prop="deviceType" label="类型-型号" show-overflow-tooltip width="180">
					<template #default="{ row }">
						<span>{{ row.deviceType }}</span>
						<span class="px-1">-</span>
						<span>{{ row.deviceModelName }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="deptName" label="所属单位" show-overflow-tooltip width="150" />
				<el-table-column prop="relateCount" label="关联设备" show-overflow-tooltip width="90" />
				<el-table-column prop="beRelateCount" label="被关联数" show-overflow-tooltip width="90" />
				<el-table-column prop="installWorker" label="安装人" show-overflow-tooltip width="90" />
				<el-table-column prop="alarmWorkerName" label="接警人" show-overflow-tooltip width="180">
					<template #default="{ row }">
						<el-button link type="primary" @click="alarmWorkerDetailDialogRef.openDialog(row.alarmWorkerId)">
							{{ row.alarmWorkerName }}-
							{{ row.alarmWorkerPhone }}
						</el-button>
					</template>
				</el-table-column>
				<el-table-column prop="createTime" label="安装时间" show-overflow-tooltip width="160" />
				<el-table-column prop="remarks" label="备注" show-overflow-tooltip width="200" />
			</el-table>
			<pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination" />
		</div>

		<!-- 编辑、新增  -->
		<form-dialog ref="formDialogRef" @refresh="getDataList(false)" />
		<!-- 解绑 -->
		<el-dialog title="操作提示" v-model="visible" :close-on-click-modal="false" width="480px">
			<div class="text-error">解除绑定后将无法收到报警和故障信息，产生的后果自行承担！确定解除绑定吗？</div>
			<div class="flex items-center mt-4">
				<span>设备是否返回给上一级：</span>
				<el-radio-group v-model="returnDept">
					<el-radio :label="10">是</el-radio>
					<el-radio :label="20">否</el-radio>
				</el-radio-group>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="visible = false">取消</el-button>
					<el-button type="primary" @click="onSubmit(selectObjs)" :disabled="loading">确认</el-button>
				</span>
			</template>
		</el-dialog>
		<!-- 安装点详情 -->
		<detail-dialog ref="detailDialogRef" @edit="handleEdit" @refresh="getDataList()" />
		<!-- 接警人详情 -->
		<AlarmWorkerDetailDialog ref="alarmWorkerDetailDialogRef" />
	</div>
</template>

<script setup lang="ts" name="systemBasicInstallLocation">
import { BasicTableProps, useTable } from '/@/hooks/table';
import { fetchList, delObjs } from '/@/api/installation/basicInstallLocation';
import { useMessage } from '/@/hooks/message';
import { deptTree } from '/@/api/admin/dept';
import { fetchListAll as fetchFloorListAll } from '/@/api/installation/basicPlaceFloor';
import { fetchListAll as fetchBuildingListAll } from '/@/api/installation/basicPlaceBuilding';
import { useRouter } from 'vue-router';

const router = useRouter();
// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
const DetailDialog = defineAsyncComponent(() => import('./components/detail.vue'));
const AlarmWorkerDetailDialog = defineAsyncComponent(() => import('./components/alarmWorkerDetail.vue'));
// 定义查询字典

// 定义变量内容
const formDialogRef = ref();
const detailDialogRef = ref();
const alarmWorkerDetailDialogRef = ref();
// 搜索变量
const queryRef = ref();
const visible = ref(false);
const loading = ref(false);
const returnDept = ref(20);
// 多选变量
const selectObjs = ref([]) as any;
const multiple = ref(true);
const parentData = ref([]);
const buildingOptions = ref<any[]>([]);
const floorOptions = ref<any[]>([]);

const state: BasicTableProps = reactive<BasicTableProps>({
	queryForm: {},
	pageList: fetchList,
	descs: ['create_time'],
	createdIsNeed: false,
});

//  table hook
const { getDataList, currentChangeHandle, sizeChangeHandle, sortChangeHandle, tableStyle } = useTable(state);

// 清空搜索条件
const resetQuery = () => {
	// 清空搜索条件
	queryRef.value?.resetFields();
	// 清空多选
	selectObjs.value = [];
	state.queryForm.imei = '';
	getDataList();
};

// 多选事件
const selectionChangHandle = (objs: { id: string }[]) => {
	selectObjs.value = objs;
	multiple.value = !objs.length;
};

const onSubmit = async (rows: any[]) => {
	try {
		loading.value = true;
		await delObjs({ ids: rows.map((d) => d.id), returnDept: returnDept.value });
		getDataList();
		useMessage().success('解绑成功！');
		visible.value = false;
		returnDept.value = 20;
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};
const getDeptData = async () => {
	deptTree().then((res) => {
		parentData.value = res.data;
	});
};

// 选择建筑物-查询楼层
const handleBuildChange = (id: string) => {
	state.queryForm.floorId = '';
	fetchFloorListAll({ buildingId: id }).then((res) => {
		floorOptions.value = res.data;
	});
};

const getBuildings = () => {
	fetchBuildingListAll().then((res) => {
		buildingOptions.value = res.data;
	});
};
getBuildings();
getDeptData();

const handleDetail = (row: any) => {
	router.push({ path: '/platform/basicDevice/facilityDetails', query: { id: row.deviceId, type: '1' } });
};

const handleBuilding = (buildingId: string) => {
	router.push({ path: '/installation/basicPlaceBuilding/index', state: { params: { buildingId } } });
};

const handleFloor = (row: { floorId: string; buildingId: string }) => {
	router.push({ path: '/installation/basicPlaceFloor/index', state: { params: { floorId: row.floorId, buildingId: row.buildingId } } });
};
const handleEdit = (data: any) => {
	formDialogRef.value.openDialog(data, true);
};
onMounted(() => {
	const params = history?.state?.params;
	params?.buildingId && (state.queryForm.buildingId = params?.buildingId);
	getDataList();
	history.state.params = undefined;
});
</script>
